/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.stock.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.stock.domain.TblTradingDateRecord;
import me.zhengjie.stock.pipeline.KlineTodayPipeline;
import me.zhengjie.stock.pipeline.StockRealTimeSpider;
import me.zhengjie.stock.service.StockSpiderService;
import me.zhengjie.stock.service.TblTradingDateRecordService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 任务调度类
 */
@Slf4j
@Service
@AllArgsConstructor
public class StockTask {

    private final StockRealTimeSpider stockRealTimeSpider;
    private final StockSpiderService stockSpiderService;
    private final TblTradingDateRecordService tblTradingDateRecordService;
    private final KlineTodayPipeline stockRealTimeSpiderBatch;

    /**
     * 监测今日交易状态 并 更新交易日记录任务
     */
    public void checkTradingDate() {
        stockRealTimeSpider.checkAndInitTradingDate();
        log.info("执行【监测今日交易状态 并 更新交易日记录任务】成功");
    }

    /**
     * 执行k线数据爬取任务(今日/最后交易日)o
     */
    public void updateTradingDateHalfCourt() {
        String todayDate = DateUtil.formatDate(new Date());
        LambdaQueryWrapper<TblTradingDateRecord> queryWrapper = new QueryWrapper<TblTradingDateRecord>().lambda();
        queryWrapper.eq(TblTradingDateRecord::getTradingDate, todayDate);
        TblTradingDateRecord tradingDateRecord = tblTradingDateRecordService.getOne(queryWrapper);
        if (tradingDateRecord == null) {
            throw new RuntimeException("交易数据拉取更新失败，交易日期[" + todayDate + "]记录不存在");
        }
        //全量拉取
        stockSpiderService.runTradingDateKlineSpider();
        log.info("执行【交易数据拉取更新任务】成功");
    }

}
